package backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 47. 全排列 II
 * User: Li_yizYa
 * Date: 2025/6/20
 * Time: 11:50
 */
public class Solution12 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return ret;
        }
        List<Integer> tmp = new ArrayList<>();
        int[] used = new int[nums.length];
        Arrays.sort(nums);
        backTracking(nums, ret, tmp, used);
        return ret;
    }
    private void backTracking(int[] nums, List<List<Integer>> ret, List<Integer> tmp, int[] used) {
        if (nums.length == tmp.size()) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 1 || used[i] == 1) {
                continue;
            }
            used[i] = 1;
            tmp.add(nums[i]);
            backTracking(nums, ret, tmp, used);
            tmp.remove(tmp.size() - 1);
            used[i] = 0;
        }
    }
}
